package com.hue.netty.day01.two;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/*
    自定义处理器:
        将客户端和服务端通信的数据类型包装为HttpObject
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest) {
            System.out.println("httpObject的类型：" + httpObject.getClass());
            System.out.println("客户端的地址：" + channelHandlerContext.channel().remoteAddress());
            HttpRequest httpRequest = (HttpRequest) httpObject;
            System.out.println("uri:" + httpRequest.uri());
            if(!httpRequest.uri().equals("/favicon.ico")){
                //响应数据给客户端
                ByteBuf buf = Unpooled.copiedBuffer("hello world!", CharsetUtil.UTF_8);
                //创建HttpResponse
                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
                //将response返回
                channelHandlerContext.writeAndFlush(response);
            }
        }
    }
}
